<template>
    <div>
        <!--
            说明：
            el-drawer 里不能加 destroy-on-close 属性，由于引入地图组件的问题，加了会造成 el-drawer 2次弹出(闪眼睛)，
            具体原因未知, 但从引入地图组件情况出发，这里也不建议加，不然每次关闭 drawer都行销毁子元素，那么二次打开
            drawer 地图都需要重新初始化加载慢耗资源，没有必要
        -->
        <el-drawer
            :title="options.row.id ? '编辑电桩' : '新增电桩'"
            :visible="options.visible"
            direction="rtl"
            size="60%"
            custom-class="pile-drawer"
            ref="drawer"
            :before-close="handleClose">
            <el-form :model="form" ref="form" id="form" label-position="right" label-width="110px" size="small" :rules="rules">
                <el-form-item label="电桩名称" prop="name">
                    <el-input type="text" placeholder="请输入电桩名称" class="input" maxlength="40" autocomplete="off" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="快速充电" prop="fast">
                    <el-input type="text" class="input" placeholder="填写数量, 无则为空或填0" maxlength="4" autocomplete="off" v-model.number="form.fast" @input="handleNumber('fast')"></el-input>
                </el-form-item>
                <el-form-item label="慢速充电" prop="slow">
                    <el-input type="text" class="input" placeholder="填写数量, 无则为空或填0" maxlength="4" autocomplete="off" v-model.number="form.slow" @input="handleNumber('slow')"></el-input>
                </el-form-item>
                <!--el-form-item label="电桩类型" prop="pile_type" class="pile_type">
                    <el-checkbox-group v-model="form.pile_type">
                        <el-checkbox label="1">快速充电</el-checkbox>
                        <el-checkbox label="2">普通充电</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="营业时间">
                    <el-form-item label="" prop="pile_time">
                        <el-radio-group v-model="form.pile_time">
                            <el-radio :label="1">全天24H</el-radio>
                            <el-radio :label="2">自定义</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="" prop="pile_time_text" v-if="form.pile_time === 2">
                        <el-input type="text" placeholder="如：周一 至 周五 9:00 ~ 18:00" class="input" maxlength="80" autocomplete="off" v-model="form.pile_time_text"></el-input>
                    </el-form-item>
                </el-form-item-->
                <el-form-item label="客服电话" prop="tel">
                    <el-input type="text" class="input" maxlength="34" autocomplete="off" v-model="form.tel"></el-input>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input type="text" class="input" maxlength="60" autocomplete="off" v-model="form.address"></el-input>
                    <el-button type="primary" @click="handleMapPoint">点击标注</el-button>
                </el-form-item>
                <el-form-item label="地图标注" prop="longitude">
                    <el-input type="text" class="input" maxlength="60" autocomplete="off" v-model="form.longitude" style="display: none"></el-input>
                    <AMap class="a-map" ref="aMapRef" :options="mapOptions" :data="mapData" @update="handleMapUpdate" />
                </el-form-item>
                <el-form-item label="" prop="pile_point">
                    <el-button size="small"
                        type="primary"
                        @click="submitForm('form')"
                        :loading="loading">
                        {{ loading ? "提交中 ..." : "确 定" }}
                    </el-button>
                    <el-button size="small" @click="closeDrawer">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script>
import AMap from '@/components/map/aMap'
export default {
    props: {
        options: {
            type: Object,
            default: () => ({
                row: {},
                visible: false
            })
        }
    },
    components: { AMap },
    data() {
        return {
            imageAccept: ['image/png'],
            imageSzie: 2,
            imageLimit: 1,
            uploadDisplay: false,
            file_list: [],
            form: {
                id: 0,
                name: "",
                fast: '',
                slow: '',
                tel: '',
                address: '',
                longitude: null,
                latitude: null
            },
            loading: false,
            rules: {
                name: [
                    { required: true, message: '请输入电桩名称', trigger: ['blur','change'] }
                ],
                address: [
                    { required: true, message: '请选择电桩地址', trigger: ['blur','change'] }
                ],
                longitude: [
                    { required: true, message: '请关联地图坐标', trigger: ['blur','change'] }
                ]
            },
            mapOptions: {    // 地图参数
                el: 'allmap1'
            },
            mapData: {}      // 地图数据
        }
    },
    methods: {
        handleNumber(val) {
            this.form[val] = this.form[val].toString().replace(/[^\d]/g, '')
        },
        handleClose(done) {
            this.$confirm('确定要关闭表单吗？')
            .then(() => this.closeDrawer())
            .catch(() => {})
        },
        closeDrawer() {
            if(this.loading) return; // 正在提交数据则禁止关闭窗口
            this.loading = false;
            this.visible = false
            this.$refs.form.resetFields();
            this.$emit("closeDrawer");
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.loading = true;
                    const url = this.form.id ? 
                    '/admin/chargingPile/index.php?act=chargingPile&op=update' :
                    '/admin/chargingPile/index.php?act=chargingPile&op=add'
                    const formData = { ...this.form }
                    if (!+formData.fast && !+formData.slow) {
                        this.loading = false;
                        return this.$message.error('快充数量 和 慢充数量不能同时为0')
                    }
                    this.$http.post(url, formData).
                    then(res => {
                        this.loading = false;
                        if(res.code == 1) {
                            this.closeDrawer();
                            this.$message.success(res.msg)
                            this.$emit("getData");
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(res => {
                        this.loading = false;
                        this.$message.error(res.msg)
                    })
                } else {
                    return false;
                }
            });
        },
        getDetail(id) {
            return this.$http.get('admin/chargingPile/index.php?act=chargingPile&op=info', { params: { id } })
        },
        handleMapPoint() {
            this.$refs.form.validateField('address', msg => {
                if (!msg) {
                    this.$refs.aMapRef.setMarker({
                        title: this.form.name,
                        content: this.form.address,
                        address: this.form.address
                    })
                }
            })
        },
        handleMapUpdate(res) {
            const { lat, lng, address, index } = res
            if (lat && lng) {
                this.form.latitude = Math.round(lat * 10**10) / 10**10
                this.form.longitude = Math.round(lng * 10**10) / 10**10
            } else if (address) {
                // ...
            }
        }
	},
	watch: {
        "options.row": {
            // immediate: true,
            handler: function(val) {
                if (val && val.id) {
                    this.getDetail(val.id).then(res => {
                        this.form = res.data
                        this.mapData = {
                            title: res.data.name,
                            content: res.data.address,
                            point: parseInt(res.data.latitude) > 0 ? {
                                lat: res.data.latitude,
                                lng: res.data.longitude
                            } : null
                        }
                    })
                } else {
                    this.form = {}
                    this.mapData = {}
                }
            }
        }
    }
}
</script>
<style lang="scss">
.pile-drawer {
    min-width: 800px;
    overflow-y: auto;
}
</style>
<style lang="scss" scoped>
.el-form { 
    padding: 0px 20px;
    .el-form-item .el-form-item {
        margin-bottom: 0;
        &:nth-child(n+2){
            margin-top: 6px;
        }
    }
    .pile_type {
        margin-bottom: 10px;
    }
    .el-input {
        max-width:  280px;
        + .el-button { margin-left: 10px; }
    }
    .a-map {
        height: calc(46vh)
    }
}
</style>
